package com.zjs.jsp.domain.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @author 李文
 * @create 2017-10-12 10:45
 **/
public class WebHelpService
{
    private static final Logger LOGGER = LoggerFactory.getLogger(WebHelpService.class);

    private static final ObjectMapper JSON = new ObjectMapper();

    /**
     * 从request中获得参数Map，并返回可读的Map
     */
    public static Map<String, String> getParameterMap(HttpServletRequest request) {
        // 参数Map
        Map properties = request.getParameterMap();
        // 返回值Map
        Map returnMap = new HashMap();
        Iterator entries = properties.entrySet().iterator();
        Map.Entry entry;
        String name = "";
        String value = "";
        while (entries.hasNext()) {
            entry = (Map.Entry) entries.next();
            name = (String) entry.getKey();
            Object valueObj = entry.getValue();
            if (null == valueObj) {
                value = "";
            } else if (valueObj instanceof String[]) {
                String[] values = (String[]) valueObj;
                for (String value1 : values) {
                    value = value1 + ",";
                }
                value = value.substring(0, value.length() - 1);
            } else {
                value = valueObj.toString();
            }
            try {
                returnMap.put(name, java.net.URLDecoder.decode(value, "utf-8"));
            } catch (Exception e) {
                returnMap.put(name, value);
            }
        }
        return returnMap;
    }

    public static String sidData(String orderkey, String secret, String sig, String uuid, Object orders) {
        // 转换成JSON
        String data;

        try {
            data = JSON.writeValueAsString(orders).replace(",\"clientFlag\":null", "");
        } catch (Exception e) {
            LOGGER.error(uuid + "  订单数据转换异常 ", e);
            return getString(50007, "接受数据无法格式化");
        }
        if (!"fales".equals(orderkey)) {
            if (orderkey.equals(sig)) {
                return null;
            }
        }
        try {
            String sigd = getSig(data, secret);
            if (!sig.equals(sigd)) {
                LOGGER.error(uuid + " 验证签名失败 接受的 sig ：" + sig + "  生成的 sig : " + sigd, new Exception("验证签名失败"));
                return getString(40002, "验证签名失败");
            }
        } catch (Exception e) {
            LOGGER.error(uuid + "sig.equals(getSig(data)  接受数据无法格式化 ", e);
            return getString(50007, "接受数据无法格式化");
        }
        return null;
    }


    public static String getSig(String data, String secret) throws Exception {
        MessageDigest md = MessageDigest.getInstance("SHA-1");
        data = secret + data + secret;
        byte[] digest = md.digest(data.getBytes("UTF-8"));// 对接后的字符串进行sha1加密
        System.out.println(digest);
        StringBuffer hexString = new StringBuffer();
        // 字节数组转换为 十六进制 数 的 字符串
        for (byte aDigest : digest) {
            String shaHex = Integer.toHexString(aDigest & 0xFF);
            if (shaHex.length() < 2) {
                hexString.append(0);
            }
            hexString.append(shaHex);
        }
        return hexString.toString().toUpperCase();
    }

    public static String getString(Integer code, String msg) {
        return "{\"code\": " + code + ",\"msg\": \"" + msg + "\",\"data\": null}";
    }

    public static String getString(Integer code, String msg, String data) {
        return "{\"code\": " + code + ",\"msg\": \"" + msg + "\",\"data\": " + data + "";
    }

}
